import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_widget_from_html_core/flutter_widget_from_html_core.dart';
import 'package:get/get.dart';
import 'package:yysk_app/model/pay_model/user_list_pay_certification_model.dart';
import 'package:yysk_app/pages/main/main_page.dart';
import 'package:yysk_app/pages/nft_pages/wallet_pages/wallet_personal/wallet_personal_controller.dart';
import 'package:yysk_app/routes/global_controller.dart';
import 'package:yysk_app/utils/colors.dart';
import 'package:yysk_app/utils/helper.dart';
import 'package:yysk_app/widget/button_widget.dart';
import 'package:yysk_app/widget/checkbox_widget.dart';
import 'package:yysk_app/widget/custom_app_bar2.dart';
import 'package:oktoast/oktoast.dart';
import 'package:yysk_app/widget/image_asset_widget.dart';
import 'withdraw_controller.dart';

class WithdrawPage extends GetView<WithdrawController> {
  static const path = '/withdraw';
  const WithdrawPage({super.key});

  @override
  Widget build(BuildContext context) {
    final double top = MediaQuery.of(context).padding.top;
    GlobalController globalController = Get.find();

    return Scaffold(
      resizeToAvoidBottomInset: false,
      backgroundColor: AppColors.backgroundColorBlack,
      body: Stack(
        children: [
          Positioned(
            top: 0,
            left: 0,
            right: 0,
            child: ImageAssetWidget(
              width: 375.px,
              height: 812.px,
              imageUrl: 'static/images/bg.png',
            ),
          ),
          Padding(
            padding: EdgeInsets.fromLTRB(0, top, 0, 24.px),
            child: Column(
              children: [
                CustomAppBar2(
                  title: '提现',
                  context: context,
                  beforBack: () {
                    try {
                      WalletPersonalController walletPersonalController =
                          Get.find();
                      walletPersonalController.getPlatWallet().then((res) {
                        Get.back();
                      });
                    } catch (e) {
                      if (Navigator.canPop(context)) {
                        Get.back();
                      } else {
                        Get.offAllNamed(MainPage.path);
                      }
                    }
                  },
                ),
                Expanded(
                  child: Obx(
                    () => Padding(
                      padding: EdgeInsets.symmetric(
                        horizontal: 16.px,
                        vertical: 0,
                      ),
                      child: ListView(
                        padding: EdgeInsets.zero,
                        children: [
                          hiSpace(height: 20.px),
                          Container(
                            padding: EdgeInsets.only(bottom: 16.px),
                            decoration: BoxDecoration(
                              color: Color.fromRGBO(31, 33, 38, 0.62),
                              borderRadius: BorderRadius.circular(10.px),
                              // border: Border.all(
                              //   width: 1.px,
                              //   color: Color.fromRGBO(255, 255, 255, 0.1),
                              // ),
                            ),
                            child: Column(
                              children: [
                                Container(
                                  padding: EdgeInsets.fromLTRB(
                                    16.px,
                                    18.px,
                                    16.px,
                                    16.px,
                                  ),
                                  decoration: BoxDecoration(
                                    color: AppColors.backgroundColorBlackLight,
                                    borderRadius: BorderRadius.circular(10.px),
                                  ),
                                  child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      Text(
                                        '提现金额',
                                        style: TextStyle(
                                          fontSize: 12.px,
                                          fontWeight: FontWeight.bold,
                                          color: AppColors.fontColorSearchEE,
                                        ),
                                      ),
                                      SizedBox(height: 18.px),
                                      Row(
                                        children: [
                                          Expanded(
                                            child: TextField(
                                              controller:
                                                  controller.amountController,
                                              keyboardType:
                                                  TextInputType.numberWithOptions(
                                                    decimal: true,
                                                  ),
                                              style: TextStyle(
                                                fontSize: 24.px,
                                                color:
                                                    AppColors.fontColorSearchEE,
                                              ),
                                              decoration: const InputDecoration(
                                                border: InputBorder.none,
                                                hintText: '',
                                              ),
                                              onChanged: (value) {
                                                if (value != '' &&
                                                    double.parse(value) <=
                                                        double.parse(
                                                          controller
                                                              .detailInfo
                                                              .value!
                                                              .balance!,
                                                        )) {
                                                  controller.timer?.cancel();
                                                  if (isLastCharDot(value))
                                                    return;
                                                  controller.timer = Timer(
                                                    Duration(seconds: 2),
                                                    () {
                                                      controller.getManei();
                                                    },
                                                  );
                                                } else {
                                                  if (value == '' &&
                                                      isLastCharDot(value)) {
                                                  } else {
                                                    showToast('请输入合理的提现金额');
                                                  }
                                                }
                                              },
                                              inputFormatters: [
                                                FilteringTextInputFormatter(
                                                  RegExp("[0-9.]"),
                                                  allow: true,
                                                ),
                                                MyNumberTextInputFormatter(
                                                  digit: 2,
                                                ),
                                              ],
                                            ),
                                          ),
                                        ],
                                      ),
                                      Divider(
                                        color: AppColors.backgroundColorGreyF8,
                                      ),
                                      hiSpace(height: 16.px),
                                      Obx(
                                        () => Row(
                                          children: [
                                            Text(
                                              '账户余额：${controller.detailInfo.value?.balance ?? '0.00'}, ',
                                              style: TextStyle(
                                                fontSize: 12.px,
                                                color: AppColors.fontColor,
                                              ),
                                            ),
                                            GestureDetector(
                                              onTap: controller.withdrawAll,
                                              child: Text(
                                                '全部提现',
                                                style: TextStyle(
                                                  color:
                                                      AppColors.fontColorSearch,
                                                  fontSize: 12.px,
                                                ),
                                              ),
                                            ),
                                          ],
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                                hiSpace(height: 16.px),
                                Padding(
                                  padding: EdgeInsets.only(
                                    left: 16.px,
                                    right: 16.px,
                                  ),
                                  child: Column(
                                    children: [
                                      Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.spaceBetween,
                                        children: [
                                          Text(
                                            '提现服务费',
                                            style: TextStyle(
                                              color:
                                                  AppColors.fontColorSearchEE,
                                              fontSize: 12.px,
                                            ),
                                          ),
                                          Text(
                                            '-${controller.feeAmount.value ?? 0.00}',
                                            style: TextStyle(
                                              color:
                                                  AppColors.fontColorSearchEE,
                                              fontSize: 12.px,
                                            ),
                                          ),
                                        ],
                                      ),
                                      hiSpace(height: 6.px),
                                      Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.spaceBetween,
                                        children: [
                                          Text(
                                            '预计到账',
                                            style: TextStyle(
                                              color:
                                                  AppColors.fontColorSearchEE,
                                              fontSize: 12.px,
                                            ),
                                          ),
                                          Text(
                                            '${controller.getPrice.value ?? 0.00}',
                                            style: TextStyle(
                                              color:
                                                  AppColors.fontColorSearchEE,
                                              fontSize: 12.px,
                                            ),
                                          ),
                                        ],
                                      ),
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          ),
                          SizedBox(height: 32.px),
                          Text(
                            '选择接收钱包',
                            style: TextStyle(
                              fontSize: 12.px,
                              color: AppColors.fontColorSearchEE,
                            ),
                          ),
                          hiSpace(height: 10.px),
                          ...controller.listPayCertification.map((e) {
                            return _walletCard(item: e!, context);
                          }),

                          Padding(
                            padding: EdgeInsets.fromLTRB(0.px, 20.px, 0.px, 0),
                            child: HtmlWidget(
                              controller.detailInfo.value?.withdrawDesc ?? '',
                              textStyle: TextStyle(
                                color: AppColors.fontColorGray99,
                                fontSize: 12.px,
                              ),
                            ),
                            // SizedBox(
                            //   width: double.infinity,
                            //   child: Column(
                            //     mainAxisAlignment: MainAxisAlignment.start,
                            //     crossAxisAlignment: CrossAxisAlignment.start,
                            //     children: [
                            //       Text(
                            //         '温馨提示：',
                            //         style: TextStyle(
                            //           fontSize: 12.px,
                            //           color: AppColors.fontColorGray99,
                            //         ),
                            //       ),
                            //       hiSpace(height: 6.px),
                            //       Text(
                            //         '1 单笔提现金额范围为：100元-20000元',
                            //         style: TextStyle(
                            //           fontSize: 12.px,
                            //           color: AppColors.fontColorGray99,
                            //         ),
                            //       ),
                            //       hiSpace(height: 6.px),
                            //       Text(
                            //         '2 每笔提现手续费1%；',
                            //         style: TextStyle(
                            //           fontSize: 12.px,
                            //           color: AppColors.fontColorGray99,
                            //         ),
                            //       ),
                            //       hiSpace(height: 6.px),
                            //       Text(
                            //         '3 提现金额请一下100元为基础，1元的倍数递增；',
                            //         style: TextStyle(
                            //           fontSize: 12.px,
                            //           color: AppColors.fontColorGray99,
                            //         ),
                            //       ),
                            //       hiSpace(height: 6.px),
                            //       Text(
                            //         '4 到账时间为工作日T+1到账；工作日内发起的提现为次日的24点前到账；若次日为非工作日，则顺延到下一个工作日次日的24点前到账。',
                            //         style: TextStyle(
                            //           fontSize: 12.px,
                            //           color: AppColors.fontColorGray99,
                            //         ),
                            //       ),
                            //       hiSpace(height: 6.px),
                            //     ],
                            //   ),
                            // ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
                Obx(
                  () =>
                      controller.detailInfo.value?.isAvailable == true
                          ? Column(
                            children: [
                              ButtonWidget(
                                label: '确认提现',
                                height: 40.px,
                                width: 347.px,
                                fontSize: 16.px,
                                fontColor: AppColors.fontColor21,
                                onPressed: () {
                                  // 实名
                                  if (globalController.hasAuth.value == false) {
                                    controller.toOpenWallet();
                                    return;
                                  }
                                  // 设置交易密码
                                  if (globalController
                                          .user
                                          .value
                                          ?.transactionPassword ==
                                      null) {
                                    controller.isSetPayPassword();
                                    return;
                                  }

                                  controller.isOpenWallet();
                                },
                              ),
                              SizedBox(height: 20.px),
                            ],
                          )
                          : SizedBox(),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _walletCard(
    BuildContext context, {
    required UserListPayCertificationModel item,
  }) {
    return Container(
      width: context.width,
      padding: EdgeInsets.fromLTRB(20.px, 21.px, 20.px, 21.px),
      margin: EdgeInsets.only(bottom: 10.px),
      decoration: BoxDecoration(
        color: AppColors.backgroundColorBlackLight,
        borderRadius: BorderRadius.circular(8.px),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Text(
            '智付钱包',
            style: TextStyle(
              fontSize: 16.px,
              color: AppColors.fontColorSearchEE,
            ),
          ),
          hiSpace(width: 12.px),
          CheckboxWidget(onChanged: (value) {}, checked: true, size: 18),
        ],
      ),
    );
  }

  bool isLastCharDot(String? str) {
    return str != null && !str.isEmpty && str.endsWith('.');
  }
}

class MyNumberTextInputFormatter extends TextInputFormatter {
  static const defaultDouble = 0.001;

  ///允许的小数位数，-1代表不限制位数
  int digit;
  MyNumberTextInputFormatter({this.digit = -1});
  static double strToFloat(String str, [double defaultValue = defaultDouble]) {
    try {
      return double.parse(str);
    } catch (e) {
      return defaultValue;
    }
  }

  ///获取目前的小数位数
  static int getValueDigit(String value) {
    if (value.contains(".")) {
      return value.split(".")[1].length;
    } else {
      return -1;
    }
  }

  @override
  TextEditingValue formatEditUpdate(
    TextEditingValue oldValue,
    TextEditingValue newValue,
  ) {
    String value = newValue.text;
    int selectionIndex = newValue.selection.end;
    if (value == ".") {
      value = "0.";
      selectionIndex++;
    } else if (value == "-") {
      value = "-";
      selectionIndex++;
    } else if (value != "" &&
            value != defaultDouble.toString() &&
            strToFloat(value, defaultDouble) == defaultDouble ||
        getValueDigit(value) > digit) {
      value = oldValue.text;
      selectionIndex = oldValue.selection.end;
    }
    return new TextEditingValue(
      text: value,
      selection: new TextSelection.collapsed(offset: selectionIndex),
    );
  }
}
